const HttpHelper = require('./httpHelper');

module.exports={
    //权重随机
    weightRandom(arr){
        //arr=[{name:'a',weight:10},{name:'b',weight:20}]
        var total = 0;
        var i, j, weight;
        //下标标记数组，按照上面的例子，单倍情况下其组成为[1,2,2,3,4,4]
        var index = new Array();
        for (i = 0; i < arr.length; i++) {
            //判断元素的权重，为了实现小数权重，先将所有的值放大100倍
            weight = 'undefined' != typeof(arr[i].weight) ? parseInt(arr[i].weight*100) : 0;
            for (j = 0; j < weight; j++) {
                index.push(i);
            }
            total += weight;
        }
        //随机数值，其值介于0-5的整数
        var rand = Math.floor(Math.random() * total);
        return arr[index[rand]];
    },
    //计算两个时间相差多少天
    calcDetailDay(time1,time2){
        var startTime = new Date(time1.getFullYear()+'-'+(time1.getMonth()+1)+'-'+time1.getDate()).getTime();
        var endTime = new Date(time2.getFullYear()+'-'+(time2.getMonth()+1)+'-'+time2.getDate()).getTime();
        return  Math.floor((endTime-startTime)/(3600*1000*24))
    },
    //将对象的某个属性转成数组
    ObjectToArray(obj,propertyName){
        let result=[];
        let keys=Object.keys(obj);
        for(let i=0;i<keys.length;i++){
            result.push(obj[keys[i]][propertyName]);
        }
        return result;
    },
    //将对象的某个属性转成数组,并去除重复
    ObjectToArrayDistinct(obj,propertyName){
        let result=[];
        let keys=Object.keys(obj);
        for(let i=0;i<keys.length;i++){
            let propertyValue=obj[keys[i]][propertyName];
            if(result.indexOf(propertyValue)<0){
                result.push(propertyValue);
            }
        }
        return result;
    },
    // 获取一段字符串
    getRandName(len=10){
        let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        chars.sort((a, b) => Math.random() - 0.5);
        return chars.join('').slice(0, len);
    },
    // 通过code获取opendid
    async getSessionKey(appid, appsecret, loginType, code, anonymous_code){
        let url = '';
        switch(parseInt(loginType)){
            case 105 : url = `https://api.q.qq.com/sns/jscode2session?appid=${appid}&secret=${appsecret}&js_code=${code}&grant_type=authorization_code`; break;
            case 120 : url = `https://developer.toutiao.com/api/apps/jscode2session?appid=${appid}&secret=${appsecret}&code=${code}&anonymous_code=${anonymous_code}`; break;
            default  : url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appsecret}&js_code=${code}&grant_type=authorization_code`; break;
        }
        let sessionKeyResultStr = await HttpHelper.getLocal(url);
        // console.log('sessionKeyResultStr =', sessionKeyResultStr);
        return JSON.parse(sessionKeyResultStr);
    }
};